package com.iwgang.familiarrecyclerview.baservadapter;

import ohos.agp.components.*;
import ohos.app.Context;

import java.util.List;

/**
 * FamiliarBaseAdapter
 */
public abstract class FamiliarBaseAdapter<T> extends BaseItemProvider {
    protected Context mContext;
    protected List<T> mDatas;
    protected     LayoutScatter mInflater;
    private final int           layoutId;
    private       int           displayCount;

    public FamiliarBaseAdapter(Context context, List<T> datas) {
        this(context , datas , -1);
    }

    public FamiliarBaseAdapter(Context context, List<T> datas, int layoutId) {
        this.mContext = context;
        this.mDatas = datas;
        this.layoutId = layoutId;
        mInflater = LayoutScatter.getInstance(mContext);
    }

    @Override
    public int getCount() {
        if (displayCount != 0) {
            return this.displayCount;
        }
        return mDatas.size();
    }

    public List<T> getData() {
        return mDatas;
    }

    public int getDataSize() {
        return mDatas.size();
    }

    public void setDisplayCount(int displayCount) {
        this.displayCount = displayCount;
    }

    @Override
    public T getItem(int position) {
        return mDatas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public void add(T d) {
        int startPos = mDatas.size();
        mDatas.add(d);
        notifyDataSetItemChanged(startPos);
    }

    public void addAll(List<T> data) {
        int curSize = mDatas.size();
        mDatas.addAll(data);
        if (curSize == 0) {
            notifyDataChanged();
        } else {
            notifyDataSetItemRangeChanged(curSize, data.size());
        }
    }

    public void remove(T d) {
        if (mDatas.contains(d)) {
            int posIndex = mDatas.indexOf(d);
            mDatas.remove(d);
            notifyDataSetItemRemoved(posIndex);
        }
    }

    public void remove(int index) {
        if (mDatas.size() > index) {
            mDatas.remove(index);
            notifyDataSetItemRemoved(index);
        }
    }

    public boolean contains(T d) {
        return mDatas.contains(d);
    }

    public void clear() {
        mDatas.clear();
        notifyDataChanged();
    }

    public void replaceAll(List<T> data) {
        mDatas.clear();
        mDatas.addAll(data);
        notifyDataChanged();
    }

    @Override
    public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
        ViewHolder holder = ViewHolder.get(mContext, componentContainer,
                layoutId, position);
        convert(holder, getItem(position));
        return holder.getConvertView();
    }

    public abstract void convert(ViewHolder holder, T t);
}
